<?php
class action extends mysql
{
	private $book;		//book表
	private $btype;		//图书分类表
	private $reader;	//读者表
	private $rtype;		//读者等级表
	private $borrow;	//借还表
	
	public function __construct()
	{
		parent::__construct();
		$this->book   = PREFIX . 'book';
		$this->btype  = PREFIX . 'btype';
		$this->reader = PREFIX . 'reader';
		$this->rtype  = PREFIX . 'rtype';;
		$this->borrow  = PREFIX . 'borrow';
	}

	public function get_nav()
	{
		$res = $this->_selects("SELECT * FROM `{$this->btype}` WHERE `show`=1 LIMIT 0, 8");
		return $res ? $res : false;
	}
	
   /**
	*函数: _get_hot_books()
	*功能: 读取热门借阅图书
	*参数: 条数
	*返回: 失败返回false
	*/
	public function _get_hot_books($num = 5)
	{
		$query = "select * from `{$this->book}` where `del`=0 order by `times` desc limit 0," . $num;
		if($res = $this->_selects($query))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}
	
   /**
	*函数: _get_tuijian()
	*功能: 读取推荐图书（5）
	*参数: 无
	*返回: 失败返回false
	*/
	public function _get_tuijian($num = 5)
	{
		$query = "select * from `{$this->book}` where `del`=0 and `tuijian`=1 limit 0," . (int)$num;
		if($res = $this->_selects($query))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}
	
   /**
	*函数: _get_click()
	*功能: 读取总排行（5）
	*参数: 无
	*返回: 失败返回false
	*/
	public function _get_click($num = 5)
	{
		$query = "select * from `{$this->book}` where `del`=0 order by `click` desc limit 0," . (int)$num;
		if($res = $this->_selects($query))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}

   /**
	*函数: _get_class()
	*功能: 读取所有图书分类。//统计其子分类中所有图书总和
	*参数:  无
	*返回: 失败返回false
	*/
	public function _get_class()
	{
		
		$query = sprintf("select * from `{$this->btype}` where `show`=2 OR `show`=1");
		if($res = $this->_selects($query))
		{
			$num = count($res);
			for($i = 0; $i <$num; $i++)
			{
				$sql = sprintf("select * from `{$this->book}` where `typeid`=%d and `del`=0", $res[$i]['id']);
				$res[$i]['counts'] = count($this->_selects($sql));
			}
			return $res;
		}
		else
		{
			return false;
		}
	}

   /**
	*函数: _get_new_books($num)
	*功能: 读取最新添加图书
	*参数: $num
	*返回: 失败返回false
	*/
	public function _get_new_books($num = 5)
	{
		$query = sprintf("select * from `{$this->book}` where `del`=0  order by `indate` desc limit 0,%d", $num);
		if($res = $this->_selects($query))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}
	
   /**
	*函数: _read_count_books()
	*功能: 读取所有书的数目
	*参数: 无
	*返回: 失败返回false
	*/
	public function _read_count_books()
	{
		$query = "select * from `{$this->book}` where `del`=0";
		$res = $this->_selects($query);
		return count($res);
	}	
	
   /**
	*函数: _get_fenlei()
	*功能: 读取所有分类//统计旗下的所有图书
	*参数: null
	*返回: 失败返回false
	*/
	public function _get_fenlei()
	{
		$query = "select id,concat(fid,'-',id) as fid, value, description from `{$this->btype}` order by fid asc";
		if($res = $this->_selects($query))
		{
			$count = count($res);
			for($i = 0; $i <$count; $i++)
			{
				$sql = sprintf("select * from `{$this->book}` where `typeid`=%d and `del`=0", $res[$i]['id']);
				$res_sql = $this->_selects($sql);
				$res[$i]['counts'] = count($res_sql);
				$num = count(explode('-', $res[$i]['fid'])) - 2;
				$res[$i]['value'] = '├' . str_repeat('──',$num) . $res[$i]['value'];
			}
			return $res;
		}
		else
		{
			return false;
		}
	}

   /**
	*函数: _get_type_name($id)
	*功能: 读取指定分类
	*参数: $id
	*返回: 失败返回false
	*/
	public function _get_type_name($id)
	{
		if($id == false)
		{
			return;
		}
		$query = sprintf("select * from `{$this->btype}` where `id`=%d", $id);
		if($res = $this->_select($query))
		{
			$r = '&nbsp;&gt;&gt;&nbsp;<a href="book_by_class.php?typeid=' . $res['id'] . '">' . $res['value'] . '</a>';			
			return $r;
		}
		else
		{
			return;
		}
	}
	
   /**
	*函数: _get_book_in_type($id)
	*功能: 读取一个分类下的所有文章
	*参数: $id
	*返回: 失败返回false
	*/
	public function _get_book_in_type($id)
	{
		global $page;					//当前页	
		$offset = ($page-1)*DISPLAY;	//数据库查询偏移量
		$arr = '';
		if($id == false)
		{
			$query1 = "select * from `{$this->book}` where `del`=0 limit {$offset}, " . DISPLAY;
			$query2 = "select * from `{$this->book}` where `del`=0";
		}
		else
		{
			$query1 = sprintf("select * from `{$this->book}` where `del`=0 and `typeid`=%d limit {$offset}, %d", $id, DISPLAY);
			$query2 = sprintf("select * from `{$this->book}` where `del`=0 and `typeid`=%d", $id);
		}
		if($arr[0] = $this->_selects($query1))
		{
			$arr[1] = count($this->_selects($query2));	//总记录数
			return $arr;
		}
		else
		{
			return false;
		}
	}

   /**
	*函数: _get_book_read($bookid)
	*功能: 读取一个文章
	*参数: $bookid
	*返回: 失败返回false
	*/
	public function _get_book_read($bookid)
	{
		$sql = sprintf("select * from `{$this->book}` where `del`=0 and `bid`=%d", $bookid);
		if($res = $this->_select($sql))
		{
			if($_SESSION['click'] == '')		//通过session防止重复
			{
				$query = sprintf("update `{$this->book}` set `click`=`click`+1 where `bid`=%d", $bookid);
				$this->_update($query);
			}
			else
			{
				$_SESSION['click'] = 1;
			}
			
			$res['pdate'] = d($res['pdate']);
			$res['indate'] = d($res['indate']);
			return $res;
		}
	}
/*--------------------------------图书借阅页面----------------------------------------------*/

   /**
	*函数: _get_reader_info($id)
	*功能: 读取用户信息
	*参数: 条数
	*返回: 失败返回false
	*/
	public function _get_reader_info($id)
	{
		$sql = sprintf("select * from `{$this->reader}` left join `{$this->rtype}` on 
					   `{$this->reader}`.`type`=`{$this->rtype}`.`typeid` where `{$this->reader}`.`id`=%d", $id);
		if($res = $this->_select($sql))
		{
			$res['lasttime'] = d($res['lasttime']);
			return $res;
		}
	}

   /**
	*函数: _get_reader_collect($arr)
	*功能: 读取用户收藏的文章
	*参数: $arr
	*返回: 失败返回false
	*/
	public function _get_reader_collect($arr)
	{
		if(empty($arr))
		{
			return $res = '';
		}
		$sql = "select * from `{$this->book}` where ";
		foreach($arr as $v)
		{
			$sql .= sprintf("`bid`=%d or ", $v);
		}
		$sql = substr($sql, 0, -3);
		if($res = $this->_selects($sql))
		{
			return $res;
		}
	}
	
   /**
	*函数: _get_reader_borrow($arr)
	*功能: 读取用户借的书(未归还的图书)
	*参数: $arr
	*返回: 失败返回false
	*/
	public function _get_reader_borrow($uesrid)
	{
		$sql = sprintf("select * from `{$this->borrow}` left join `{$this->book}` on 
					   `{$this->borrow}`.`bookid`=`{$this->book}`.`bid` 
					   where `{$this->borrow}`.`readerid`=%d and `{$this->borrow}`.`isback`=0", $uesrid);
		if($res = $this->_selects($sql))
		{
			return $res;
		}
	}

   /**
	*函数: _get_guoqi($userid)
	*功能: 读取过期未归还的图书)
	*参数: $arr
	*返回: 失败返回false
	*/
	public function _get_guoqi($userid)
	{
		$sql = sprintf("select * from `{$this->borrow}` left join `{$this->book}` on 
					   `{$this->borrow}`.`bookid`=`{$this->book}`.`bid` 
					   where `{$this->borrow}`.`readerid`=%d and 
					   `{$this->borrow}`.`isback`=0 and
					   `{$this->borrow}`.`backdate`<%d", $userid, time());
		if($res = $this->_selects($sql))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}
	
   /**
	*函数: borrow_book($id, $userid)
	*功能: 借书动作
	*参数: $arr
	*返回: 失败返回false
	*/
	public function borrow_book($id, $userid)
	{
		$sql0 = sprintf("select * from `{$this->borrow}` where `readerid`=%d and `bookid`=%d", $userid, $id);
		if($res0 = $this->_select($sql0))
		{
			$this->msg('book_view.php?bookid=' . $id, '已经借过此书，请不要重复借阅');
		}
		$sql1 = sprintf("select * from `{$this->book}` where `bid`=%d", $id);
		if($res1 = $this->_select($sql1))
		{
			if($res1['storage'] <=0)
			{
				$this->msg('book_view.php?bookid=' . $id, '抱歉，此书暂无可借复本！');
			}
		}
		$date = time();
		//检查用户是否已经超过最大借阅
		$query = sprintf("select * from `{$this->reader}`,`{$this->rtype}` where `type`=`typeid` and `id`= %d", $userid);
		if($res = $this->_select($query))
		{
			$max_borrow = $res['max_borrow'];	//最大借阅
			$total      = $res['total'];		//当前借阅数
			$collect    = explode(',', $res['collect']);		//收藏夹
		}
		if($total>= $max_borrow)
		{
			$this->msg('book_view.php?bookid=' . $id, '抱歉，超过最大借阅数量（' . $max_borrow . '&nbsp;本），无法完成借阅');
		}
		//可以借阅
		$query1 = sprintf("update `{$this->reader}` set `total`=`total`+1 where `id`=%d", $userid);	//借阅加1
		$query2 = sprintf("update `{$this->book}` set `storage`=`storage`-1, `times`=`times`+1 where `bid`=%d", $id);	//库存减一,借阅量加1
		$query3 = sprintf("insert into `{$this->borrow}` (`id`, `readerid`, `bookid`, `borrowdate`, `backdate`,`isback`, `goon`) 
						  values('', %d, %d, %d, %d, 0, 0)", $userid, $id, $date, $date + 30*24*60*60);
		if($this->_update($query1) && $this->_update($query2) && $this->_insert($query3))
		{
			$this->msg('book_view.php?bookid=' . $id, '恭喜！借阅成功！');
		}
	}


   /**
	*函数: collect_moveout($id, $userid)
	*功能: 移除收藏夹动作
	*参数: $arr
	*返回: 失败返回false
	*/
	public function collect_moveout($bid, $userid)
	{
		$tmp = '';
		$sql = sprintf("select * from `{$this->reader}` where `id`=%d", $userid);
		if($res = $this->_select($sql))
		{
			$collect = explode(',', $res['collect']);	//收藏夹
		}
		if(in_array($bid, $collect))
		{
			foreach($collect as $v)
			{
				if($v != $bid)
				{
					$tmp[] = $v;
				}
			}
		}
		if(count($tmp)> 1)
		{
			$up_c  = implode(',', $tmp);
		}
		else
		{
			$up_c = '';		//收藏夹置空
		}
		$query = sprintf("update `{$this->reader}` set `collect`='%s' where `id`=%d", $up_c, $userid);
		if($this->_update($query))
		{
			$this->msg('book_borrow_back.php', '移除成功！');
		}
	}

   /**
	*函数: collect_add($id, $userid)
	*功能: 添加到收藏夹动作
	*参数: $arr
	*返回: 失败返回false
	*/
	public function collect_add($id, $userid)
	{
		$sql = sprintf("select * from `{$this->reader}` where `id`=%d", $userid);
		if($res = $this->_select($sql))
		{
			$collect = !empty($res['collect']) ? explode(',', $res['collect']) : '';	//收藏夹
		}
		if($collect != '' && in_array($id, $collect))
		{
			$this->msg('book_view.php?bookid=' . $id, '你已经收藏过此书啦！');
		}
		$collect[] = intval($id);
		natsort($collect);
		$up_c = implode(',', $collect);
		$query = sprintf("update `{$this->reader}` set `collect`='%s' where `id`=%d", $up_c, $userid);
		if($this->_update($query))
		{
			$this->msg('book_view.php?bookid=' . $id, '添加到收藏夹成功成功！');
		}
	}
	
   /**
	*函数: goon_borrow($id, $userid)
	*功能: 续借图书
	*参数: $arr
	*返回: 失败返回false
	*/
	public function goon_borrow($id, $userid)
	{
		$sql = sprintf("select * from `{$this->borrow}` where `readerid`=%d and `bookid`=%d", $userid, $id);
		if($res = $this->_select($sql))
		{
			$goon = $res['goon'];
		}
		if($goon == 1)
		{
			$this->msg('book_borrow_back.php', '续借失败！已经续借！');
		}
		$query = sprintf("update `{$this->borrow}` set `goon`=1 , `backdate`=`backdate`+%d  
						 where `readerid`=%d and `bookid`=%d", 15*24*60*60, $userid, $id);
		if($this->_update($query))
		{
			$this->msg('book_borrow_back.php', '续借成功！');
		}
	}
	
   /**
	*函数: book_back($id, $userid)
	*功能: 归还图书
	*参数: $arr
	*返回: 失败返回false
	*/
	public function book_back($id, $userid)
	{
		$query = sprintf("delete from `{$this->borrow}` 
						 where `readerid`=%d and `bookid`=%d", $userid, $id);
		$query2 = sprintf("update `{$this->reader}` set `total`=`total`-1 where `id`=%d", $userid);	//借书总量减一
		$query3 = sprintf("update `{$this->book}` set `storage`=`storage`+1 where `bid`=%d", $id);	//图书数量加一
		if($this->_delete($query) && $this->_update($query2) && $this->_update($query3))
		{
			$this->msg('book_borrow_back.php', '成功归还图书！');
		}
	}

   /**
	*函数: search_fun($_POST)
	*功能: 站内搜索图书
	*参数: $_post
	*返回: 失败返回false
	*/
	public function search_fun($in)
	{
		$kw = htmlspecialchars(mysql_real_escape_string(trim($in['search'])));
		if($kw == '' || $kw == '搜搜看')
		{
			$this->msg('index.php', '请输入要搜索的内容');
		}
		switch($in['type'])
		{
			case 'name':
				$sql = sprintf("select * from `{$this->book}` left join `{$this->btype}` on 
							   `{$this->book}`.`typeid`=`{$this->btype}`.`id` where `{$this->book}`.`del`=0 and 
							   `{$this->book}`.`name` like '%%%s%%'", $kw);
				$rep = 'name';
				break;
			case 'pstore':
				$sql = sprintf("select * from `{$this->book}` left join `{$this->btype}` on 
							   `{$this->book}`.`typeid`=`{$this->btype}`.`id` where `{$this->book}`.`del`=0 and 
							   `{$this->book}`.`pstore` like '%%%s%%'", $kw);
				$rep = 'pstore';
				break;
			case 'typeid':
				$sql = sprintf("select * from `{$this->book}` left join `{$this->btype}` on 
							   `{$this->book}`.`typeid`=`{$this->btype}`.`id` where `{$this->book}`.`del`=0 and 
							   `{$this->btype}`.`value` like '%%%s%%'", $kw);
				$rep = 'value';
				break;
		}
		if($res = $this->_selects($sql))
		{
			$total = count($res);
			foreach($res as $k=>$v)
			{
				foreach($v as $key=>$val)
				{
					$res[$k][$key] = preg_replace("/($kw)/i", '<font style="color:#FF0000;font-size:14px;">\\1</font>', $val);
				}
			}
		}
		$res[]['total'] = $total;
		return $res;
	}

   /**
	*函数: _get_userinfo($userid)
	*功能: 读取用户信息
	*参数: 用户登录名
	*返回: 失败返回false
	*/
	public function _get_userinfo($user)
	{
		$sql = sprintf("select * from `{$this->reader}` where `userid`='%s'", mysql_real_escape_string($user));
		if($res = $this->_select($sql))
		{
			return $res;
		}
		else
		{
			return false;
		}
	}
	
   /**
	*函数: _edit_userinfo($ar)
	*功能: 编辑用户信息
	*参数: 用户输入的个人信息
	*返回: 失败返回false
	*/
	public function _edit_userinfo($arr)
	{
		if($arr['eusername'] == '')
		{
			$this->msg('login.php?action=change&uid' . $arr['uid'], '用户名不能为空！');
		}
		if(!preg_match('/^\w+@\w+\.\w+/i', $arr['eemail']))
		{
			$this->msg('login.php?action=change&uid' . $arr['uid'], '邮箱格式不正确！');
		}
		if(empty($arr['epwd1']) && empty($arr['epwd2']))
		{
			$query = sprintf("update `{$this->reader}` set `username`='%s', `email`='%s', `sex`='%s' where `userid`='%s'",
							 mysql_real_escape_string($arr['eusername']),
							 mysql_real_escape_string($arr['eemail']),
							 mysql_real_escape_string($arr['sex']),
							 mysql_real_escape_string($arr['uid']));
		}
		else if(!empty($arr['epwd1']) && !empty($arr['epwd2']))
		{
			$query = sprintf("update `{$this->reader}` set `username`='%s', `email`='%s', `sex`='%s',`password`=sha1('%s') where `userid`='%s'",
				 mysql_real_escape_string($arr['eusername']),
				 mysql_real_escape_string($arr['eemail']),
				 mysql_real_escape_string($arr['sex']),
				 mysql_real_escape_string($arr['epwd2']),
				 mysql_real_escape_string($arr['uid']));
		}
		if($this->_update($query))
		{
			$this->msg('book_borrow_back.php', '恭喜，修改成功！');
		}
		else
		{
			$this->msg('book_borrow_back.php', '未修改任何内容！');
		}
	}

   /**
	*函数: _reg_user($ar)
	*功能: 注册用户
	*参数: 用户输入的个人信息
	*返回: 失败返回false
	*/
	public function _reg_user($ar)
	{
		$sql = sprintf("select * from `{$this->reader}` where `userid`='%s'", $ar['ruserid']);
		if($res = $this->_select($sql))
		{
			$this->msg('login.php?action=register', '用户名已经被注册了，请更换用户名！');
		}
		$query = sprintf("insert into `{$this->reader}` 
						 (`id`,`userid`,`username`,`password`,`email`,`sex`,`lasttime`,`lastip`,`type`,`total`,`collect`)
						 values('','%s','%s',sha1('%s'),'%s','%s',%d,'%s',10,0,'')",
						 $ar['ruserid'],
						 $ar['rname'],
						 $ar['rpwd2'],
						 $ar['remail'],
						 $ar['rsex'],
						 time(),
						 $_SERVER['REMOTE_ADDR']
						 );
		if($res = $this->_insert($query))
		{
			$_SESSION['reader'] = $ar['ruserid'];	//登录成功
			$_SESSION['readerid'] = $res;
			$this->msg('index.php', '恭喜你！用户&nbsp;' . $ar['ruserid'] . '&nbsp;注册成功！');
		}
	}
/*--------class end--------------------*/
}
?>